<?php
/**
 * 测试分类、渠道和支付方式与公司绑定的功能
 */

// 检查常量是否已定义
if (!defined("Site_Name")) define("Site_Name","Project-D");
if (!defined("Site_Url")) define("Site_Url","http://127.0.0.2");
if (!defined("Site_Lang")) define("Site_Lang","utf8");
if (!defined("Site_Db")) define("Site_Db","localhost");
if (!defined("Site_Dbuser")) define("Site_Dbuser","ydd");
if (!defined("Site_Dbpass")) define("Site_Dbpass","aBs22t7d2KAZiajt");
if (!defined("Site_Dbname")) define("Site_Dbname","ydd");

// 尝试连接数据库
try {
    $conn = new PDO(
        'mysql:host='.Site_Db.';dbname='.Site_Dbname,
        Site_Dbuser, 
        Site_Dbpass,
        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
    );
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "数据库连接成功\n";
    
    // 测试表结构
    $tables = array('categories', 'sources', 'paymethods');
    
    echo "\n===== 测试表结构 =====\n";
    foreach ($tables as $table) {
        echo "\n表: $table\n";
        
        // 检查表是否存在company_id列
        $stmt = $conn->prepare("SHOW COLUMNS FROM $table LIKE 'company_id'");
        $stmt->execute();
        $columnInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($columnInfo) {
            echo "✓ company_id列存在\n";
            echo "  类型: {$columnInfo['Type']}\n";
            echo "  空值: {$columnInfo['Null']}\n";
            echo "  默认值: {$columnInfo['Default']}\n";
        } else {
            echo "✗ company_id列不存在\n";
        }
    }
    
    // 测试查询
    echo "\n===== 测试查询 =====\n";
    
    // 查询companies表获取一个有效的company_id用于测试
    $stmt = $conn->prepare("SELECT id FROM companies LIMIT 1");
    $stmt->execute();
    $companyData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($companyData) {
        $testCompanyId = $companyData['id'];
        echo "使用测试company_id: $testCompanyId\n";
        
        foreach ($tables as $table) {
            echo "\n测试查询 $table 表:\n";
            try {
                $stmt = $conn->prepare("SELECT COUNT(*) FROM $table WHERE company_id = :company_id");
                $stmt->execute([':company_id' => $testCompanyId]);
                $count = $stmt->fetchColumn();
                echo "✓ 查询成功，找到 $count 条记录\n";
            } catch (PDOException $e) {
                echo "✗ 查询失败: " . $e->getMessage() . "\n";
            }
        }
    } else {
        echo "未找到可用的公司ID，跳过查询测试\n";
    }
    
    echo "\n===== 测试完成 =====\n";
    
} catch (PDOException $e) {
    die("数据库操作失败: " . $e->getMessage());
}